package com.example.api.controller;

import com.example.api.model.TbConfig;
import com.example.api.service.ApiService;
import com.example.api.util.RateLimiterUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @program: api_limit
 * @description: 演示接口层
 * @author: Mr.chen
 * @create: 2020-02-18 19:12
 **/
@RestController
@RequestMapping("/test")
@Slf4j
public class DemoController {

    @Autowired
    private ApiService apiService;

    @GetMapping("api-limit")
    public void apiLimit(String apiName, String userId) throws Exception{
        Long time = apiService.getConfigValue(TbConfig.CONFIG_TIME);
        Integer times = Math.toIntExact(apiService.getConfigValue(TbConfig.CONFIG_TIMES));
        if (RateLimiterUtil.accessCheck(apiName, userId, times, time)) {
            System.out.println("do something...");
            RateLimiterUtil.accessConsume(apiName, userId, times, time);
        } else {
            System.out.println("请求超次数限制");
        }
    }
}
